//
//  AppDelegate.m
//  Meboo
//
//  Created by kyo on 2023/10/7.
//
#import "AppDelegate.h"
#import "FirebaseCore/FirebaseCore.h"
#import "FIRMessaging.h"
#import "IQKeyboardManager.h"
#import <RongCloudOpenSource/RongIMKit.h>
#import <RongIMLib/RCIMClient.h>
#import <StoreKit/StoreKit.h>
#import <AppsFlyerLib/AppsFlyerLib.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/ASIdentifierManager.h>
#import <UserNotifications/UserNotifications.h>
//#import "NSWelcomeViewController.h"
#import "NSConversationViewController.h"
#import "Meboo-Swift.h"
#import "MBThumbnailCache.h"
#import "BaseNotificationView.h"
#import "MBNotificationView1.h"
#import "MBNotificationView2.h"
#import "MBNotificationView3.h"
#import "MBNotificationView4.h"
#import "MBNotificationView5.h"
#import <EBCustomBannerView.h>
#import "KLPaymentManager.h"
//im
#import "NSChatListViewController.h"
#import "NSConversationViewController.h"
@interface AppDelegate ()
<
RCIMConnectionStatusDelegate,
RCIMUserInfoDataSource,
RCIMReceiveMessageDelegate,
SKPaymentTransactionObserver,
UNUserNotificationCenterDelegate,
FIRMessagingDelegate
>
@property (strong, nonatomic) NSMutableArray <EBCustomBannerView *>*bannerArr;
@end

@implementation AppDelegate
NSString *const kGCMMessageIDKey = @"AQ83645557";

//https://apps.apple.com/cn/app/id6471480825
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSLog(@"本机idfv=%@",[UIDevice currentDevice].identifierForVendor.UUIDString);//控制台查看
    [self setRongCloud];
//    [self getRongCloudToken];
//    [FIRApp configure];
    [self setFirebase];
    
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
        UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
    [[UNUserNotificationCenter currentNotificationCenter]
        requestAuthorizationWithOptions:authOptions
        completionHandler:^(BOOL granted, NSError * _Nullable error) {
          // ...
        if (granted) {
            //点击允许
            [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
                
            }];
        } else {
            NSLog(@"");
        }
        /**
         埋点 code
         通知授权上报 503
         权限打开500 没打开501
         */
        [[NSIOApiManager sharedManager] setIOWithCode:@"503" content:granted ? @"500" : @"501"];
        }];

    [application registerForRemoteNotifications];
    
    [MBNotificationCenter addObserver:self selector:@selector(resetNoti) name:REGISTER_UPLOADPHOTO_BEGIN object:nil];
    
    
    //清除角标
//    if (@available(iOS 16.0, *)) {
//        [[UNUserNotificationCenter currentNotificationCenter] setBadgeCount:0 withCompletionHandler:nil];
//    }else {
//        [application setApplicationIconBadgeNumber:0];
//    }
    
    
    [self setAppsFlyer];
    
    [self getVipState];
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    self.window.rootViewController = [[BaseNavViewController alloc] initWithRootViewController:[[WelcomeViewController alloc]init]];
    

    application.delegate = self;

    
#pragma MARK --- 键盘设置
    //键盘设置
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;//控制整个功能是否启用
    manager.shouldResignOnTouchOutside = YES;//控制点击背景是否收起键盘
    manager.shouldToolbarUsesTextFieldTintColor = YES;//控制键盘上的工具条文字颜色是否用户自定义
    manager.enableAutoToolbar = YES;//控制是否显示键盘上的工具条
    
    
    //续订支付代理
//    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    [[KLPaymentManager sharePaymentManager] restorePurchaase];
    
    return YES;
}

//iOS15以后广告标识符在此处调用 如果写在didFinishLaunchingWithOptions 不会弹窗
- (void)applicationDidBecomeActive:(UIApplication *)application {
//    if (@available(iOS 14.0, *)) {
//        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
//            NSString *idfaStr = [ASIdentifierManager sharedManager].advertisingIdentifier.UUIDString;
//            NSLog(@"ad:%@",idfaStr);
//        }];
//    }else{
//        // iOS14以下版本依然使用老方法
//        // 判断在设置-隐私里用户是否打开了广告跟踪
//        //设置-隐私-广告-限制广告跟踪关闭
//        if ([ASIdentifierManager sharedManager].isAdvertisingTrackingEnabled) {
//            NSString *idfaStr = [ASIdentifierManager sharedManager].advertisingIdentifier.UUIDString;
//        }
//    }
    
    
    
    if (@available(iOS 14, *)) {
            // iOS14及以上版本需要先请求权限
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
                    // 获取到权限后，依然使用老方法获取idfa
                    if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
                        NSString *idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
                        NSString *idfb = [ASIdentifierManager sharedManager].advertisingIdentifier.UUIDString;
                        NSLog(@"idfa = %@,idfb = %@",idfa,idfb);
                    } else {
                        NSLog(@"请在设置-隐私-跟踪中允许App请求跟踪");
                    }
                }];
            });
        } else {
            // iOS14以下版本依然使用老方法
            // 判断在设置-隐私里用户是否打开了广告跟踪
            if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
                NSString *idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
                NSLog(@"idfa = %@",idfa);
            } else {
                NSLog(@"请在设置-隐私-广告中打开广告跟踪功能");
            }
        }
    
//    [[AppsFlyerLib shared] waitForATTUserAuthorizationWithTimeoutInterval:60];
//    [[AppsFlyerLib shared] start];
}

- (void)setFirebase {
    [FIRApp configure];
//    [[FIRApp setena]
//    [FIRMessaging messaging].autoInitEnabled = YES;
    [FIRMessaging messaging].delegate = self;
    [[FIRMessaging messaging] tokenWithCompletion:^(NSString *token, NSError *error) {
      if (error != nil) {
        NSLog(@"Error getting FCM registration token: %@", error);
      } else {
        NSLog(@"FCM registration token: %@", token);
//        self.fcmRegTokenMessage.text = token;
      }
    }];
}

- (void)setRongCloud {
    
    NSString *appKey = MBRongCloud; // example: bos9p5rlcm2ba
    RCInitOption *initOption = [[RCInitOption alloc] init];
    //新加坡:RCAreaCodeSG 北美:RCAreaCodeNA
    initOption.areaCode = RCAreaCodeNA;

    [[RCIM sharedRCIM] initWithAppKey:appKey option:initOption];
    [RCIM sharedRCIM].enablePersistentUserInfoCache = YES;
    //设置发送的消息是否携带用户信息
        [RCIM sharedRCIM].enableMessageAttachUserInfo = YES;
    /// 添加代理委托
    [[RCIM sharedRCIM] addConnectionStatusDelegate:self];
    [[RCIM sharedRCIM] setUserInfoDataSource:self];
    [RCIM sharedRCIM].receiveMessageDelegate = self;
}

- (void)onRCIMReceiveMessage:(RCMessage *)message left:(int)left {
    MBUserAccount  *account = [MBUserAccount defaultAccount];
    [[RCCoreClient sharedCoreClient] getTotalUnreadCountWith:^(int unreadCount) {
        [[RCCoreClient sharedCoreClient] getUnreadCount:ConversationType_PRIVATE targetId:[MBUserAccount defaultAccount].kefuTargetId completion:^(int count) {
            dispatch_async(dispatch_get_main_queue(), ^{
                account.unReadNum = unreadCount-count;
                [MBUserAccount  saveAccount:account];
                // 非主线程，将UI操作切换到主线程进行
                [[NSNotificationCenter defaultCenter] postNotificationName:UPDATE_MESSAGE_UNREAD object:nil];
            });
        }];
    }];
    
    //离线消息不处理
    if (message.isOffLine) {
        return;
    }
    
    __WeakSelf
    //获取用户信息
    [[MBChatDataManager sharedManager] getUserInfoWithUserId:message.targetId completion:^(RCUserInfo * _Nonnull userInfo) {
        [[RCIM sharedRCIM] refreshUserInfoCache:userInfo withUserId:message.targetId];
        [weakSelf dealPopViewReceiveMessage:message userInfo:userInfo];
    }];
}

- (void)dealPopViewReceiveMessage:(RCMessage *)message userInfo:(RCUserInfo *)userInfo {
    if ([self.currentViewController isKindOfClass:[NSChatListViewController class]] || [self.currentViewController isKindOfClass:[NSConversationViewController class]]) {
        return;
    }
    
    //处理自定义通知弹窗
    //在此处收到了推送信息, 拿到关键信息,弹出自定义信息
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:userInfo.name forKey:@"title"];
    [dict setObject:message.content.conversationDigest forKey:@"body"];
    //用户头像
    [dict setObject:userInfo.portraitUri forKey:@"image"];
    [dict setObject:message.targetId forKey:@"targetId"];
    
    
    BaseNotificationView *view = [BaseNotificationView new];
    if ([message.objectName isEqualToString:@"RC:TxtMsg"]) {
        view = [MBNotificationView1 new];
    } else if ([message.objectName isEqualToString:@"RC:ImgMsg"]) {
        RCImageMessage *imageMessage = (RCImageMessage*)message.content;
        [dict setObject:imageMessage.imageUrl forKey:@"imageUrl"];
        view = [MBNotificationView2 new];
        view.isBlurred = [message.expansionDic[@"isPrivate"] boolValue];
    } else if ([message.objectName isEqualToString:@"RC:SightMsg"]) {
        RCSightMessage *signMessage = (RCSightMessage*)message.content;
        if (signMessage.thumbnailImage) {
            [dict setObject:signMessage.thumbnailImage forKey:@"imageUrl"];
        } else {
            UIImage *image = [[MBThumbnailCache sharedCache] getThumbnailImageForKey:signMessage.remoteUrl];
            if (image == nil) {
                image = [[MBThumbnailCache sharedCache] getThumbnailImage:signMessage.remoteUrl];
                [[MBThumbnailCache sharedCache] setThumbnailImage:image forKey:signMessage.remoteUrl];
                [dict setObject:image forKey:@"imageCache"];
            }
        }
        view = [MBNotificationView3 new];
        view.isBlurred = [message.expansionDic[@"isPrivate"] boolValue];
    }
    view.dict = dict;
    view.frame = CGRectMake(MBWidthScale(10), StatusBarHeight-MBHeightScale(3), ScreenWidth-MBWidthScale(20), MBHeightScale(82));
    
    EBCustomBannerView *bannerView = [EBCustomBannerView showCustomView:view block:^(EBCustomBannerViewMaker *make) {
        //       make.portraitFrame = CGRectMake(MBWidthScale(-5), MBHeightScale(20), ScreenWidth-MBWidthScale(0), MBHeightScale(82));//frame in portrait
        make.portraitMode = EBCustomViewAppearModeTop;//appear from top in portrait
        make.soundID = 1312;
        make.stayDuration = 3.0;
        //......
    }];
    
    [self.bannerArr addObject:bannerView];
    __WeakSelf
    view.hideBlock = ^{
        if (weakSelf.bannerArr.count > 0) {
            for (EBCustomBannerView *bannerView in weakSelf.bannerArr) {
                [bannerView hide];
            }
        }
        [weakSelf.bannerArr removeAllObjects];
    };
    
    view.clickBlock = ^{
        if (weakSelf.bannerArr.count > 0) {
            for (EBCustomBannerView *bannerView in weakSelf.bannerArr) {
                [bannerView hide];
            }
        }
        [weakSelf.bannerArr removeAllObjects];
        
        NSConversationViewController *conversationVC = [[NSConversationViewController alloc] initWithConversationType:ConversationType_PRIVATE targetId:message.targetId];
//        conversationVC.isSayHi = YES;
        UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
                    UINavigationController *navController = tabBarController.selectedViewController;
        [navController pushViewController:conversationVC animated:YES];
    };
}



- (void)getRongCloudToken {
    [[MBChatDataManager sharedManager] getRongCloudToken:^(BOOL success) {
        
    }];
}

- (void)getUserInfoWithUserId:(NSString *)userId completion:(void (^)(RCUserInfo *))completion {
    //开发者调自己的服务器接口，根据 userID 异步请求用户信息
    [[MBChatDataManager sharedManager] getUserInfoWithUserId:userId completion:^(RCUserInfo * _Nonnull userInfo) {
        return completion(userInfo);
    }];
}

- (void)setAppsFlyer {
    [[AppsFlyerLib shared] setAppsFlyerDevKey:@"GRYmCbW2mUt5Qitw6v4AVc"];
    [[AppsFlyerLib shared] setAppleAppID:@"6471480825"];
    [AppsFlyerLib shared].isDebug = true;
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     selector:@selector(sendLaunch:)
     name:UIApplicationDidBecomeActiveNotification
     object:nil];
    
    /**
     埋点 code
     appsflyer 初始化 606
     */
    [[NSIOApiManager sharedManager] setIOWithCode:@"1001" content:@"AppsFlyer init"];
}

- (void)sendLaunch:(UIApplication *)application {
    [[AppsFlyerLib shared] startWithCompletionHandler:^(NSDictionary<NSString *,id> *dictionary, NSError *error) {
            if (error) {
                NSLog(@"%@", error);
                return;
            }
            if (dictionary) {
                NSLog(@"%@", dictionary);
                if (![MBUserAccount defaultAccount].isUserType) {
                    [[MBLoginDataManager sharedManager] getAppsFlyersStateWithUid:[[AppsFlyerLib shared] getAppsFlyerUID] success:^(BOOL success) {
                        
                    }];
                    NSLog(@"uid = %@",[[AppsFlyerLib shared] getAppsFlyerUID]);
                }
                return;
            }
        }];
}

- (void)getVipState {
    [[MBLoginDataManager sharedManager] getUserInfoWithCode:@"" success:^(BOOL success) {
        
    }];
    [[MBMineDataManager sharedManager] getUserPrivateInfo:^(BOOL success) {
        
    }];
    
    if ([[MBUserAccount defaultAccount].userFlag integerValue] == 0) {
        /**
         埋点 code
         非注册当日首次启动APP 402
         */
        [[NSIOApiManager sharedManager] setIOWithCode:@"402" content:@"LOCATION_PERMISSION_GRANT_PAGE_WITH_APP_LAUNCH"];
    }
}

#pragma MARK --- delegate
- (void)onRCIMConnectionStatusChanged:(RCConnectionStatus)status {
    NSLog(@"");
}

//- (void)paymentQueue:(nonnull SKPaymentQueue *)queue updatedTransactions:(nonnull NSArray<SKPaymentTransaction *> *)transactions {
//    NSLog(@"");
//}

- (void)paymentQueue:(nonnull SKPaymentQueue *)queue updatedTransactions:(nonnull NSArray<SKPaymentTransaction *> *)transactions { 
    NSLog(@"");
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
  // If you are receiving a notification message while your app is in the background,
  // this callback will not be fired till the user taps on the notification launching the application.
  // TODO: Handle data of notification

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // [START_EXCLUDE]
  // Print message ID.
  if (userInfo[kGCMMessageIDKey]) {
    NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  }
  // [END_EXCLUDE]

  // Print full message.
  NSLog(@"%@", userInfo);
}

//自定义通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
//    __WeakSelf
  NSDictionary *userInfo = notification.request.content.userInfo;
    //在此处收到了推送信息, 拿到关键信息,弹出自定义信息
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:[NSString stringWithFormat:@"%@",userInfo[@"aps"][@"alert"][@"title"]] forKey:@"title"];
    [dict setObject:[NSString stringWithFormat:@"%@",userInfo[@"aps"][@"alert"][@"body"]] forKey:@"body"];
    [dict setObject:[NSString stringWithFormat:@"%@",userInfo[@"fcm_options"][@"image"]] forKey:@"image"];
    [dict setObject:[NSString stringWithFormat:@"%@",userInfo[@"imageUrl"]] forKey:@"imageUrl"];
    [dict setObject:[NSString stringWithFormat:@"%@",userInfo[@"targetId"]] forKey:@"targetId"];
    
    NSString *type = [NSString stringWithFormat:@"%@",userInfo[@"type"]];
    
    BaseNotificationView *view = [BaseNotificationView new];
    if ([type integerValue] < 6) {
        return;
    }
    switch ([type integerValue]) {
        case 1:
            view = [MBNotificationView1 new];
            break;
        case 2:
            view = [MBNotificationView2 new];
            break;
        case 3:
            view = [MBNotificationView2 new];
            view.isBlurred = YES;
            break;
        case 4:
            view = [MBNotificationView3 new];
            break;
        case 5:
            view = [MBNotificationView3 new];
            view.isBlurred = YES;
            break;
        case 6:
            view = [MBNotificationView4 new];
            break;
        case 7:
            view = [MBNotificationView4 new];
            view.isBlurred = YES;
            break;
        case 8:
            view = [MBNotificationView5 new];
            break;
            
        default:
            break;
    }
    view.dict = dict;
    view.frame = CGRectMake(MBWidthScale(10), StatusBarHeight-MBHeightScale(3), ScreenWidth-MBWidthScale(20), MBHeightScale(82));

    if (type.length > 0) {
        EBCustomBannerView *bannerView = [EBCustomBannerView showCustomView:view block:^(EBCustomBannerViewMaker *make) {
    //       make.portraitFrame = CGRectMake(MBWidthScale(-5), MBHeightScale(20), ScreenWidth-MBWidthScale(0), MBHeightScale(82));//frame in portrait
           make.portraitMode = EBCustomViewAppearModeTop;//appear from top in portrait
           make.soundID = 1312;
           make.stayDuration = 6.0;
           //......
        }];
        
        view.clickBlock = ^{
            [bannerView hide];
        };
    } else {
          completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionAlert);
    }
    
    

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // [START_EXCLUDE]
  // Print message ID.
//  if (userInfo[kGCMMessageIDKey]) {
//    NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
//  }
  // [END_EXCLUDE]

  // Print full message.
  NSLog(@"%@", userInfo);

  // Change this to your preferred presentation option
//  completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionAlert);
}
// Handle notification messages after display notification is tapped by the user.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void(^)(void))completionHandler {
  NSDictionary *userInfo = response.notification.request.content.userInfo;
  if (userInfo[kGCMMessageIDKey]) {
    NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  }

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // Print full message.
  NSLog(@"%@", userInfo);

  completionHandler();
}

// [END ios_10_message_handling]

// [START refresh_token]
- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken {
    NSLog(@"FCM registration token: %@", fcmToken);
    // Notify about received token.
    NSDictionary *dataDict = [NSDictionary dictionaryWithObject:fcmToken forKey:@"token"];
    [[NSNotificationCenter defaultCenter] postNotificationName:
     @"FCMToken" object:nil userInfo:dataDict];
    // TODO: If necessary send token to application server.
    // Note: This callback is fired at each app startup and whenever a new token is generated .
}
// [END refresh_token]

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  NSLog(@"Unable to register for remote notifications: %@", error);
}

// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs device token can be paired to
// the FCM registration token.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  NSLog(@"APNs device token retrieved: %@", deviceToken);
    [FIRMessaging messaging].APNSToken = deviceToken;
  // With swizzling disabled you must set the APNs device token here.
  // [FIRMessaging messaging].APNSToken = deviceToken;
}

- (void)resetNoti {
    NSUserDefaults *userDefault = [[NSUserDefaults alloc] initWithSuiteName:@"group.meboo"];
    NSMutableDictionary *dict = [userDefault valueForKey:@"notiDict"];
    NSLog(@"0909090909%@",dict);
}

- (NSMutableArray<EBCustomBannerView *> *)bannerArr {
    if (!_bannerArr) {
        _bannerArr = [NSMutableArray array];
    }
    return _bannerArr;
}
@end
